import utils from "./utils.js";
// 引入工具类函数
import {login,getSearchBanner,getRecruitAll} from "./request.js";
// 调用函数发送请求
(async function(){
    let res = await login();
    let token = res.data.token;
    localStorage.setItem("token",token);

    // 获取搜索页轮播图数据
    let banner = await getSearchBanner();
    let bannerArr = banner.data.Carousels
    bannerFn(bannerArr);

    // 获取职位模块数据
    let jobData = await getRecruitAll();
    let jobArrAll = jobData.data.rows;
    let jobArr = jobArrAll.filter((item)=>{
        return item.id < 100;
    });
    let copyJobArr = jobArr.map((item)=>{
        return item;
    });
    let newJobArr = jobArr.concat((copyJobArr));
    // 打乱顺序
    // newJobArr.sort(function(){
    //     return Math.random()-0.5;
    // });

    // 职位信息和分页器共有变量
    const size = 10, // 每页显示的个数
      totalPage = Math.ceil(newJobArr.length / size),//总页数
      pageCount = 6;//页数按钮数量
    let current = 1;
    pageFn(newJobArr,current,size,totalPage,pageCount);

    // 招聘职位总数量渲染
    let sum = document.querySelector('.job_sum');
    sum.innerText = newJobArr.length;

    // 筛选地点数据
    let cityArr = newJobArr.map((item)=>{
        return item.address;
    });
    cityArr = [...new Set(cityArr)].sort();
    cityFn(cityArr);

    // 职业类别数据
    let ategoryArr = newJobArr.map((item)=>{
        return item.requirement;
    });
    ategoryArr = [...new Set(ategoryArr)].sort();
    ategoryFn(ategoryArr);

    // 分别获取左边上下的input框元素 并创建一个空数组
    let addressInput = document.querySelectorAll('.work_city > ul input');
    let ategoryInput = document.querySelectorAll('.job_ategory_select > ul  input');
    let clearBtn = document.querySelector('.clearBtn');
    let inputData = new Array();
    let totalNum = '',checkedNum = 0;//totalNum是新的总页数，checkedNum是选中的input框数量
    addressInput.forEach((item)=>{
        item.addEventListener('click',()=>{
            if(item.checked){//如果是true则选中数量++，并且将该选中的对应的数据push进新数组中
                checkedNum++;
                inputData.push(newJobArr.filter(ele=>{return ele.address == item.parentElement.innerText}));
                ategoryInput.forEach((ate_item)=>{//如果职业类别那有勾选的则进来，过滤数据
                    if(ate_item.checked){
                        inputData=([...new Set(inputData.filter((ele)=>{return ele.requirement == ate_item.parentElement.innerText && ele.address == item.parentElement.innerText}))]);
                    };
                });
            }else{//否则选中数量--，新数组过滤掉未勾选的数据
                checkedNum--;
                inputData = inputData.filter((ele)=>{return ele.address !== item.parentElement.innerText});
                ategoryInput.forEach((ate_item)=>{
                    if(ate_item.checked){
                        inputData.push(newJobArr.filter(ele=>{return ele.requirement == ate_item.parentElement.innerText}));
                    };
                });
            };
            inputData= inputData.flat(Infinity);//扁平化处理
            totalNum = Math.ceil(inputData.length / size);

            if(checkedNum!==0){//如果数量不等于0，说明有勾选的,就渲染勾选的相关数据
                clearBtn.classList.add('cursorPoin');
                clearBtn.disabled = false; 
                pageFn(inputData,current,size,totalNum,pageCount);

            }else{//否者就是没有勾选，渲染全部数据
                clearBtn.classList.remove('cursorPoin');
                clearBtn.disabled = true;
                pageFn(newJobArr,current,size,totalPage,pageCount);
            };
        });
    });
    ategoryInput.forEach((item)=>{
        item.addEventListener('click',()=>{
            if(item.checked){
                checkedNum++;
                inputData.push(newJobArr.filter(ele=>{return ele.requirement == item.parentElement.innerText}));
                addressInput.forEach((add_item)=>{
                    if(add_item.checked){
                        inputData=([...new Set(inputData.filter((ele)=>{return ele.address == add_item.parentElement.innerText && ele.requirement == item.parentElement.innerText}))]);
                    };
                });
            }else{
                checkedNum--;
                inputData = inputData.filter((ele)=>{return ele.requirement !== item.parentElement.innerText});
                addressInput.forEach((add_item)=>{
                    if(add_item.checked){
                        inputData.push(newJobArr.filter(ele=>{return ele.address == add_item.parentElement.innerText}));
                    };
                });
            };
            inputData= inputData.flat(Infinity);
            totalNum = Math.ceil(inputData.length / size);

            if(checkedNum!==0){//如果数量不等于0，说明有勾选的
                clearBtn.classList.add('cursorPoin');
                clearBtn.disabled = false;
                pageFn(inputData,current,size,totalNum,pageCount);
            }else{//否者就是没有勾选，渲染全部数据
                clearBtn.classList.remove('cursorPoin');
                clearBtn.disabled = true;
                pageFn(newJobArr,current,size,totalPage,pageCount);
            };
        });
    });
    clearBtn.addEventListener('click',()=>{ 
        addressInput.forEach(item=>{item.checked = false});
        ategoryInput.forEach(item=>{item.checked = false});
        clearBtn.classList.toggle('cursorPoin');
        clearBtn.disabled = true;
        checkedNum = 0;
        pageFn(newJobArr,current,size,totalPage,pageCount);
    }); 
})();
// 网页vw/vh宽高计算函数
function Ant_Group($w) {
    return ($w / 1451) * 100 + "vw";
}

// 获取 头部轮播图 元素
let banner = document.querySelector('.swiper-wrapper');
// 轮播图 渲染函数
function bannerFn(data){
    let str = "";
    data.forEach(item => {
        str +=`
        <div class="swiper-slide"><img src="${item.url}" alt=""></div>
        `;
    });
    banner.innerHTML = str;
};
// swiper
let leftBtn = document.querySelector('.swiper-button-prev');
let rightBtn = document.querySelector('.swiper-button-next');
var mySwiper = new Swiper ('.swiper', {
    direction: 'horizontal', // 垂直切换选项
    observer:true,//修改swiper自己或子元素时，自动初始化swiper
    observeParents:true,//修改swiper的父元素时，自动初始化swiper
    // 如果需要前进后退按钮
    navigation: {
      nextEl: '.swiper-button-next',
      prevEl: '.swiper-button-prev',
    },
    on: {
        slideChange: function () {
            // 获取当前活动下标
            var index = this.realIndex;
            index !==0 ? leftBtn.style.opacity = "1" : leftBtn.style.opacity = "0";
            index !==2 ? rightBtn.style.opacity = "1" : rightBtn.style.opacity = "0";
        },
    },
});

// 职位信息渲染函数
let job = document.querySelector('.job_infoBox');
function jobFn(data,current,size){
    let str = '';
    data.forEach((item,index)=>{      
        if(index >= (current - 1) * size && index < current * size){
            str += `
            <div class="job_info_container">
            <div class="job_block_info">
            <!-- 信息标题 -->
            <div class="info_title">
            <a href="#">${item.salary.replaceAll(/<[^>]+>/g,"")}</a>
                <div class="info_title_spanText">
                    <span>2022-12-30</span><span>发布</span>
                </div>
            </div>
            <!-- 职位概述 -->
            <div class="info_summary">
                <div class="info_summary_span">
                    <span><i class="iconfont icon-dingwei"></i></span>
                    <span>${item.address}</span>
                    <span>|</span>
                    <span><i class="iconfont icon-briefcase"></i></span>
                    <span>${item.name}</span>
                </div>
                <button class="expand_btn open_btn">
                    <span><i class="iconfont icon-sanjiaoxia"></i></span>
                    <span>展开</span>
                </button>
                <button class="expand_btn close_btn">
                    <span><i class="iconfont icon-sanjiaoshang"></i></span>
                    <span>收起</span>
                </button>
            </div>
            <!-- 职位详细介绍 -->
            <div class="info_detailed_introduction">
                <div class="detailed_introduction_container">
                    <!-- 职位描述 -->
                    <div class="job_description">
                        ${item.desc}
                    </div>
                    <!-- 投递收藏块 -->
                    <div class="ribbon">
                        <button class="send_btn">我要投递</button>
                        <div class="collection">
                            <span><i class="iconfont icon-shoucang"></i></span>
                            <span>收藏</span>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        </div>`;
        job.innerHTML = str;
        };    
        // 职位信息展开 和 收起按钮点击事件
        const expandBtn = document.querySelectorAll('.expand_btn');
        const closeBtn = document.querySelectorAll('.close_btn');
        const openBtn = document.querySelectorAll('.open_btn');
        const details = document.querySelectorAll('.info_detailed_introduction');
        for(let i = 0;i<expandBtn.length;i++){
            expandBtn[i].addEventListener('click',function(e){
                if(e.target.className == "expand_btn open_btn"){
                    details[i/2].style.display = "block";
                    closeBtn[i/2].style.display = "block";
                    openBtn[i/2].style.opacity = 0;
                };
                if(e.target.className =="expand_btn close_btn"){
                    details[((i-1)/2)].style.display = "none";  
                    closeBtn[((i-1)/2)].style.display = "none";
                    openBtn[((i-1)/2)].style.opacity = 1;       
                };
            });
        };                 
    });
};

// 分页器渲染函数
let pageUl = document.querySelector('.job_block_pagination > ul');
function pageFn(data,current,size,totalPage,pageCount){
    jobFn(data,current,size);

    let str = `<li>
                    <button class="pagination_left_btn ${current ==1? "cursorNot" : "cursorPoin"}" ${current==1? "disabled":""}>
                        <span>
                            <i class="iconfont icon-zuojiantou"></i>
                        </span>
                    </button>
                </li>`;
    if(totalPage < 8){ // 如果总页数小于8 就直接遍历了 不需要显示左右省略按钮
        for(let i = 1; i <= totalPage;i++){
            str+=`<li><a href="#" class="pageNum ${i == current? "active":""}">${i}</a></li>`;
        };
    }else{
        // 用来保存当前选中分页前后的显示数字按钮
        let beforeNum = Math.floor(current - (pageCount - 3) / 2),
        afterNum = Math.ceil(current + (pageCount - 3) / 2);

        // 如果当前页数大于或等于5则显示左边省略号按钮
        if(current >= pageCount-1){
            str+=`<li><a href="#" class="pageNum">1</a></li>
            <li><a href="#" class="pageDot"><i class="iconfont icon-a-gengduohengxiang"></i></a></li>`;
        };

        if(current >=1 && current < pageCount -1){// 如果当前页数大于或等于1 并且 当前页 小于 5，则给前后页数按钮赋值
            beforeNum = 1;
            afterNum = pageCount-1;
        }else if(current <= totalPage && current > totalPage - (pageCount - 2)){
            beforeNum = totalPage - (pageCount -2);
            afterNum = totalPage;
        }
        for(let i = beforeNum;i <= afterNum;i++){
            str+=`<li><a href="#" class="pageNum ${i == current? "active":""}">${i}</a></li>`;
        };
    };
    if(current <= totalPage - (pageCount-2)){//当小于后等于该值则显示右按钮
        str+=`<li><a href="#" class="pageDot"><i class="iconfont icon-a-gengduohengxiang"></i></a></li>
        <li><a href="#" class="pageNum">${totalPage}</a></li>`;
    };

    

    str +=`<li>
                <button class="pagination_right_btn ${current ==totalPage? "cursorNot" : "cursorPoin"}" ${current==totalPage? "disabled":""}>
                    <span>
                        <i class="iconfont icon-youjiantou"></i>
                    </span>
                </button>
            </li>`;
    pageUl.innerHTML = str;
    let sum = document.querySelector('.job_sum');
    sum.innerText = data.length;

    // 左按钮点击事件
    const pageBtnPrev = document.querySelector('.pagination_left_btn');
    pageBtnPrev.addEventListener('click',()=>{
        if(current!==1){
            current--;
            pageFn(data,current,size,totalPage,pageCount);
        };
    });
    // 右按钮点击事件
    const pageBtnNext = document.querySelector('.pagination_right_btn');
    pageBtnNext.addEventListener('click',()=>{
        if(current!==totalPage){
            current++;
            pageFn(data,current,size,totalPage,pageCount);
        };
    });
    // 分页按钮
    const pageNumBtn = document.querySelectorAll('.pageNum ');
    pageNumBtn.forEach((item)=>{
        item.addEventListener('click',()=>{
            current = parseInt(item.innerHTML); // 因为拿到的是字符串，所以需要转换为数字类型
            pageFn(data,current,size,totalPage,pageCount);
        });
    });
};

// 工作地点和职业类别的扩展点击事件
let extend = document.querySelectorAll('.extend > .iconfont');
let cityBox = document.querySelector('.citys_box');
let ategory = document.querySelector('.job_ategory_select');
for(let i = 0;i < extend.length;i++){
    extend[i].addEventListener('click',()=>{
        if(i==0 || i==2){
            extend[i+1].style.display = "block";
            extend[i].style.display = "none";
        };
        if(i==1 || i==3){
            extend[i-1].style.display = "block";
            extend[i].style.display = "none";
        };
        if(i==0){//加
            cityBox.style.maxHeight = Ant_Group(379);
            cityBox.nextElementSibling.style.display = "block";
            cityBox.style.overflow = "visible";
        };
        if(i==1){//减
            cityBox.style.maxHeight = 0;
            cityBox.style.overflow = "hidden";
            cityBox.nextElementSibling.style.display = "none";
        };
        if(i==2){//加
            ategory.style.maxHeight = Ant_Group(379);
        };
        if(i==3){//减
            ategory.style.maxHeight = 0;
        };
    });
};

// 筛选地点渲染函数
let cityUl = document.querySelector('.work_city > ul');
function cityFn(data){
    let str = "";
    data.forEach((item,index)=>{
        if(index<10){
            str+=`
            <li><label><input type="checkbox">${item}</label></li>`;
        };
    });
    cityUl.innerHTML = str;
};

// 职业类别渲染函数
function ategoryFn(data){
    let str = "";
    data.forEach((item)=>{
        str+=`
        <li>
            <span>
                <i class="iconfont icon-sanjiaoyou"></i>
            </span>
            <label><input type="checkbox">${item}</label>
        </li>`;
    });
    ategory.firstElementChild.innerHTML = str;
};


